﻿using CastingWellEquipmentGUI.Config;
using CastingWellEquipmentGUI.Model;
using CastingWellEquipmentGUI.Utils;
using CastingWellEquipmentGUI.ViewModel.Common.Command;
using CastingWellEquipmentGUI.ViewModel.Common.LogTool;
using CastingWellEquipmentGUI.ViewModel.Common.WindowsManager;
using Confluent.Kafka;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Messaging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;

using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;

namespace CastingWellEquipmentGUI.ViewModel.Pages
{
    public class HoldingFurnacePagelViewMode : ViewModelBase
    {
        #region 变量/常量
        /// <summary>
        /// 当前窗体名称
        /// </summary>
        private const string showPageTitle = "HoldingFurnacePage";

        #endregion 变量/常量

        #region 页面属性
        /// <summary>
        /// 保温炉激光液位
        /// </summary>
        public string Label_LaserLiquidLevelOfHoldingFurnace
        {
            get { return TagTool.GetTagValueByFormNameAndControlName(showPageTitle, "Label_LaserLiquidLevelOfHoldingFurnace"); }
        }
        /// <summary>
        /// 保温炉温度反馈
        /// </summary>
        public string Label_FurnaceTemperature
        {
            get { return TagTool.GetTagValueByFormNameAndControlName(showPageTitle, "Label_FurnaceTemperature"); }
        }
        /// <summary>
        /// 保温炉倾翻速率
        /// </summary>
        public string Label_TiltingRateOfHoldingFurnace
        {
            get { return TagTool.GetTagValueByFormNameAndControlName(showPageTitle, "Label_TiltingRateOfHoldingFurnace"); }
        }
        private string _Button_TiltingRateOfHoldingFurnaceCV;
        /// <summary>
        /// CV设定
        /// </summary>
        public string Button_TiltingRateOfHoldingFurnaceCV
        {
            get { return _Button_TiltingRateOfHoldingFurnaceCV; }
            set
            {
                if (KafkaHelper.SendGatewayChangeTagMessage(showPageTitle, "Button_TiltingRateOfHoldingFurnaceCV", value))
                {
                    _Button_TiltingRateOfHoldingFurnaceCV = value;
                    RaisePropertyChanged("Button_TiltingRateOfHoldingFurnaceCV");
                    RaisePropertyChanged("Label_TiltingRateOfHoldingFurnace");
                }
            }
        }

        #region 预检测项目
        private Visibility _PreDetectionVisibility;
        /// <summary>
        /// 预检测状态
        /// 注：控制预检测框显隐
        /// </summary>
        public Visibility PreDetectionVisibility
        {
            get { return _PreDetectionVisibility; }
            set
            {
                _PreDetectionVisibility = value;
                RaisePropertyChanged("PreDetectionVisibility");
            }
        }
        /// <summary>
        /// 保温炉铝水温度正常
        /// </summary>
        public Brush Label_TheTemperatureOfAluminumWaterInHoldingFurnaceIsNormal
        {
            get
            {
                if (TagTool.GetTagValueByFormNameAndControlName(showPageTitle, "Label_TheTemperatureOfAluminumWaterInHoldingFurnaceIsNormal") == "true")
                {
                    return Brushes.Red;
                }
                return Brushes.Black;
            }
        }
        /// <summary>
        /// 保温炉倾翻保持
        /// </summary>
        public Brush Label_HoldingFurnaceOverturning
        {
            get
            {
                if (TagTool.GetTagValueByFormNameAndControlName(showPageTitle, "Label_HoldingFurnaceOverturning") == "true")
                {
                    return Brushes.Red;
                }
                return Brushes.Black;
            }
        }
        /// <summary>
        /// 保温炉准备好
        /// </summary>
        public Brush Label_HoldingFurnaceReady
        {
            get
            {
                if (TagTool.GetTagValueByFormNameAndControlName(showPageTitle, "Label_HoldingFurnaceReady") == "true")
                {
                    return Brushes.Red;
                }
                return Brushes.Black;
            }
        }
        #endregion 预检测项目

        #endregion 页面属性

        #region 定义页面执行命令
        /// <summary>
        /// 显示CV编辑框
        /// </summary>
        public DelegateCommand EditCVCommand { get; set; }
        #endregion 定义页面执行命令

        #region 线程对象
        /// <summary>
        /// 标签值变化监听线程
        /// </summary>
        private Thread tagInfoSyncThread = null;
        #endregion 线程对象

        #region 方法
        /// <summary>
        /// 构造函数
        /// </summary>
        public HoldingFurnacePagelViewMode()
        {
            // 初始化命令
            initCommand();
            // 初始化线程
            initThread();
            // 消息通道注册
            initMessenger();
            // 初始化基础信息
            initBaseSet();
        }

        /// <summary>
        /// 初始化基础信息
        /// </summary>
        private void initBaseSet()
        {
            // 页面初始化
            HashSet<Control> tempHashSet = SysCommon.getCurrentControl(showPageTitle);
            if (tempHashSet.Count > 0)
            {
                DoChanged(tempHashSet);
            }
        }

        /// <summary>
        /// 初始化命令
        /// </summary>
        private void initCommand()
        {
            // CV值设定命令
            EditCVCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(EditCVHandler)
            };
        }

        /// <summary>
        /// 初始化线程
        /// </summary>
        private void initThread()
        {
            tagInfoSyncThread = new Thread(syncThreadFunc);
            //tagInfoSyncThread.SetApartmentState(ApartmentState.STA);
            tagInfoSyncThread.IsBackground = true;
            tagInfoSyncThread.Start();
        }

        /// <summary>
        /// 消息通道注册
        /// ViewModel之间数据通信使用，整个项目全局唯一
        /// </summary>
        private void initMessenger()
        {
            //获取CV值
            Messenger.Default.Register<string>(this, "HoldingFurnaceSetCV1", (message) =>
            {
                Button_TiltingRateOfHoldingFurnaceCV = message;
            });
        }

        /// <summary>
        /// CV值设定命令
        /// </summary>
        /// <param name="obj"></param>
        private void EditCVHandler(object obj)
        {
            WindowManager.ShowModalDigitalInputPanel("SetCVPanel", "HoldingFurnaceSetCV1", Button_TiltingRateOfHoldingFurnaceCV);
        }

        /// <summary>
        /// 执行动作
        /// </summary>
        /// <param name="hashSet"></param>
        private void DoChanged(HashSet<Control> hashSet)
        {
            //遍历返回的控件信息刷新对应的控件
            foreach (Control item in hashSet)
            {
                RaisePropertyChanged(item.ControlName);
            }
        }

        /// <summary>
        /// 标签值变化监听
        /// </summary>
        private void syncThreadFunc()
        {
            // 创建消费者对象
            IConsumer<string, object> KafkaConsumer = KafkaHelper.GetConsumer();
            while (true)
            {
                if (SystemConfig.systemState == "预检测" || SystemConfig.systemState == "可见许可")
                {
                    PreDetectionVisibility = Visibility.Visible;
                }
                else
                {
                    PreDetectionVisibility = Visibility.Hidden;
                }
                // 网络中断不进行消费监听
                if (SystemConfig.SystemStatus == "网络中断")
                {
                    Thread.Sleep(1000);
                    continue;
                }
                if (ThreadController.RoundBarHoldingFurnaceThreadState)
                {
                    //开始消费
                    var result = KafkaConsumer.Consume();
                    if (result != null)
                    {
                        //手动提交
                        KafkaConsumer.Commit(result);
                        //获取消息内容
                        string tagId = result.Message.Value.ToString();
                        HashSet<Control> hashSet = KafkaHelper.UpdateCurrentUserTagValue(Int32.Parse(tagId), KafkaHelper.GetTagValueByKey(tagId.ToString()), showPageTitle);
                        if (hashSet != null)
                        {
                            DoChanged(hashSet);
                        }
                    }
                }
                Thread.Sleep(10);
            }
        }
        #endregion 方法
    }
}
